package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"net/http"
	"os"
	"os/exec"
	"strings"
)

/*
使用方法
POST http://127.0.0.1:8080/:name/:secret/*registry
name 为服务名称 例如：drone_test
secret 为通讯密码 例如：test ，可以在配置里面修改
registry 为镜像前缀 例如：registry.cn-hongkong.aliyuncs.com/asdfasdfwe/drone_test
完整示例
http://127.0.0.1:8080/drone_test/test/registry.cn-hongkong.aliyuncs.com/asdfasdfwe/drone_test
*/

// InitConfig 初始化配置
func InitConfig() {
	workDir, _ := os.Getwd()                 //获取目录对应的路径
	viper.SetConfigName("application")       //配置文件名
	viper.SetConfigType("yml")               //配置文件类型
	viper.AddConfigPath(workDir + "/config") //执行go run对应的路径配置
	//fmt.Println(workDir)
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
}

func main() {
	InitConfig()

	gin.SetMode("debug")
	r := gin.Default()
	r.POST("/:name/:secret/*registry", func(c *gin.Context) {
		secret := c.Param("secret")
		if viper.GetString("server.secret") != secret {
			jsonFail(c, "通讯密码错误", nil)
			return
		}
		name := c.Param("name")
		registry := c.Param("registry")
		registry = strings.Trim(registry, "/")

		var bd bodyData
		if err := c.ShouldBindJSON(&bd); err != nil {
			jsonFail(c, "body 参数转换失败", nil)
			return
		}

		fmt.Println("registry ", registry)
		fmt.Println("name ", name)

		// 执行命令
		cmd := exec.Command("docker", "service", "update",
			"--image",
			registry+":"+bd.Build.Tag,
			name,
		)
		err := cmd.Start() // 执行命令，不等待结果
		if err != nil {
			jsonFail(c, "cmd失败 "+err.Error(), nil)
			return
		}

		jsonSuccess(c, "成功", nil)
	})
	r.Run(":" + viper.GetString("server.port"))
}

func jsonResult(c *gin.Context, code int, msg string, data interface{}) {
	c.JSON(http.StatusOK, map[string]interface{}{
		"code": code,
		"msg":  msg,
		"data": data,
	})
}

func jsonSuccess(c *gin.Context, msg string, data interface{}) {
	jsonResult(c, 0, msg, data)
}

func jsonFail(c *gin.Context, msg string, data interface{}) {
	jsonResult(c, 1, msg, data)
}

type bodyData struct {
	Repo struct {
		Owner string `json:"owner"`
		Name  string `json:"name"`
	} `json:"repo"`
	Build struct {
		Tag      string `json:"tag"`
		Event    string `json:"event"`
		Number   int    `json:"number"`
		Commit   string `json:"commit"`
		Ref      string `json:"ref"`
		Branch   string `json:"branch"`
		Author   string `json:"author"`
		Message  string `json:"message"`
		Status   string `json:"status"`
		Link     string `json:"link"`
		DeployTo string `json:"deployTo"`
		Started  int    `json:"started"`
		Created  int    `json:"created"`
	} `json:"build"`
}
